package com.dianrui.qiyouriding.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.adapter.MessageAdapter;

import com.dianrui.qiyouriding.bean.MessageModel;
import com.dianrui.qiyouriding.event.RfreshUnread;
import com.dianrui.qiyouriding.event.RreshMsg;
import com.dianrui.qiyouriding.util.JsonUtils;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;

import com.dianrui.qiyouriding.view.SwipeMenuLayout;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的消息
 * @author
 */
@SuppressWarnings("ALL")
public class MessageActivity extends BaseActivity {
    private int mPageIndex = 1;
    private List<MessageModel> mMessageList = new ArrayList<>();
    private MessageAdapter messageAdapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    @Override
    public int getContentViewId() {
        return R.layout.activity_message;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        customInit(true, R.color.main_color);
        title.setText("我的消息");
        LinearLayoutManager layoutManager = new LinearLayoutManager(MessageActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        getMsgList(false);
        messageAdapter = new MessageAdapter(R.layout.item_message, mMessageList,MessageActivity.this);
        recyclerView.setAdapter(messageAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getMsgList( true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPageIndex++;
                getMsgList(false);
                refreshLayout.finishLoadMore();
            }
        });
        messageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MessageModel messageModel = mMessageList.get(position);
                switch (view.getId()){
                    case R.id.click_message:
                        SwipeMenuLayout layout= (SwipeMenuLayout) view.getParent();
                        TextView title=layout.findViewById(R.id.title);
                        TextView time=layout.findViewById(R.id.time);
                        TextView content=layout.findViewById(R.id.content);
                        TextView msg_show_red_dot=layout.findViewById(R.id.msg_show_red_dot);
                        ImageView msg_img=layout.findViewById(R.id.msg_img);

                        if (!layout.isExpand) {
                            readSystemMessage(messageModel.messages_id,title,time,content,msg_show_red_dot,msg_img);
                            Intent intent=new Intent(MessageActivity.this, MessageDeatilsActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("id", messageModel.messages_id);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }else {
                            layout.smoothClose();
                        }
                        break;

                    case R.id.delete:
                        delMessage(messageModel.messages_id,position);
                        break;

                    default:
                        break;
                }


            }
        });
        messageAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.click_message:
                        SwipeMenuLayout layout= (SwipeMenuLayout) view.getParent();
                        layout.smoothExpand();
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public void initData() {}

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RreshMsg rreshMsg) {
        getMsgList(true);
    }


    public void getMsgList(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("p", mPageIndex);
        OkHttpRequest.getInstance().postRequests(Url.MESSGAE, jsonObject.toString(),new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (isRfresh) {
                    mMessageList.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        String status= JsonUtils.getJsonStr(result,Constant.STATUS);
                        if (Constant.DATASUCCESS.equals(status)) {
                            String data=JsonUtils.getJsonStr(result,"data");
                            if (!StringUtils.isEmpty(data)) {
                                List<MessageModel> msglist=JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<MessageModel>>(){}.getType());
                                if (msglist != null && msglist.size()>0) {
                                    mMessageList.addAll(msglist);
                                    messageAdapter.setNewData(mMessageList);
                                    refreshLayout.setNoMoreData(false);
                                }else {
                                    messageAdapter.getData().clear();
                                    messageAdapter.setEmptyView(LayoutInflater.from(MessageActivity.this).inflate(R.layout.empty_view,null));
                                    messageAdapter.notifyDataSetChanged();
                                    ToastUtil.showToast(getString(R.string.no_data));
                                }
                            }
                        }else if (Constant.BACKLOGIN.equals(status)) {
                            SPUtils.getInstance().clear();
                            JumpKillActivitys(LoginActivity.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (mMessageList.size() <= 0) {
                        messageAdapter.getData().clear();
                        messageAdapter.setEmptyView(LayoutInflater.from(MessageActivity.this).inflate(R.layout.empty_view,null));
                        messageAdapter.notifyDataSetChanged();
                    } else {
                        recyclerView.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick(R.id.back)
    public void onViewClicked() {
        EventBus.getDefault().post(new RfreshUnread());
        finish();
    }

    //点击消息发动已读
    private void readSystemMessage(String id, final TextView title, final TextView time, final TextView content, final TextView msg_show_red_dot, final ImageView msgDot) {
        JsonObject readmsgJsonobject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            readmsgJsonobject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        readmsgJsonobject.addProperty("messages_id", id);
        OkHttpRequest.getInstance().postRequests(Url.READMESSAGE, readmsgJsonobject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                title.setTextColor(getResources().getColor(R.color.nav_color_txt));
                                time.setTextColor( getResources().getColor(R.color.nav_color_txt));
                                content.setTextColor(getResources().getColor(R.color.nav_color_txt));
                                msg_show_red_dot.setVisibility(View.INVISIBLE);
                                msgDot.setAlpha(0.7f);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    //删除消息
    private void delMessage(String messageId, final int position) {
        JsonObject delmsg = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            delmsg.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        delmsg.addProperty("messages_id", messageId);
        OkHttpRequest.getInstance().postRequests(Url.DEL_MESSGAE, delmsg.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                messageAdapter.getData().remove(position);
                                messageAdapter.setNewData(mMessageList);

                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().post(new RfreshUnread());
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mMessageList != null) {
            mMessageList.clear();
        }
    }
}
